﻿/*----------------------------------------------------------------
// Copyright (C) 2014 苏州麦迪斯顿医疗科技股份有限公司
// 文件名：NetworkAddressConnection.cs
// 文件功能描述：NetworkAddressConnection
// 创建标识：顾伟伟-2014-04-03
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CPOE.Framework.Throttling;
using System.Net;

namespace CPOE.Framework
{
    /// <summary>
    /// 一个表示网络服务器连接的类，通过向服务器发送一个HTTP GET 请求，来测试服务器是否可连接
    /// </summary>
    public class NetworkAddressConnection: Connection
    {
        public NetworkAddressConnection(NetworkAddress  address)
        {
            this.Name = address.Name;
            this.IP = address.ServerIp;
        }
        /// <summary>
        /// 更新连接状态
        /// </summary>
        public override void UpdateStatus(int timeout)
        {
            this.IsConnected = false;
            try
            {
                Uri address = new Uri(string.Format("http://{0}",this.IP));
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(address);
                request.Timeout = timeout;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    this.IsConnected = IsServerOnline(response);
                }
            }
            catch
            {
                this.IsConnected = false;
            }
            base.UpdateStatus(timeout);
        }
        /// <summary>
        /// 根据服务器的响应状态，判断服务器是否可用
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private static bool IsServerOnline(HttpWebResponse response)
        {
            bool success;
            switch (response.StatusCode)
            {
                case HttpStatusCode.Accepted:
                case HttpStatusCode.Ambiguous:
                case HttpStatusCode.Continue:
                case HttpStatusCode.Created:
                case HttpStatusCode.Forbidden:
                case HttpStatusCode.Found:
                case HttpStatusCode.LengthRequired:
                case HttpStatusCode.MethodNotAllowed:
                case HttpStatusCode.NoContent:
                case HttpStatusCode.NotModified:
                case HttpStatusCode.OK:
                case HttpStatusCode.PartialContent:
                case HttpStatusCode.RedirectKeepVerb:
                case HttpStatusCode.RedirectMethod:
                case HttpStatusCode.ResetContent:
                case HttpStatusCode.Unauthorized:
                    {
                        success = true;
                        break;
                    }
                default:
                    {
                        success = false;
                        break;
                    }
            }
            return success;
        }
    }
}
